<template>
    <div class="table-box">
        <div class="card table-search">
            <el-form label-width="auto" :inline="true">
                <el-form class="search-form">
                    <!-- 经销商名称输入框 -->
                    <el-form-item label="对比库名称">
                        <el-input v-model="initParam.compareName" placeholder="请输入对比库名称" style="width: 200px" />
                    </el-form-item>

                    <!-- 查询/重置按钮 -->
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="getTableList">搜索</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-form>
        </div>

        <div class="card ">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="openDiolg('新增', null)">新增</el-button>
                </el-col>

            </el-row>
            <div class="title head-title bottom-border">生效对比库</div>
            <div class="operation-box">
                <!-- 修改循环数据源为mockList -->
                <div class="operation-item" v-for="(item, index) in ableList" :key="item.id">
                    <div class="item-main">
                        <div class="left-info">
                            <div class="text-info">
                                <p class="shop-name">{{ item.compareName }}</p>
                                <p class="contact-info">创建于 | {{ item.createTime }}</p>
                                <p class="contact-info">共{{ item.productNums }}款产品</p> <!-- 动态显示产品数 -->
                                <p class="contact-info">共{{ item.childNums }}个系列</p> <!-- 动态显示系列数 -->
                            </div>
                        </div>
                        <div class="right-actions">
                            <!-- 状态标签与Switch组合 -->
                            <div class="status-group">
                                <span class="status-tag" :class="item.enable == 0 ? 'active' : 'inactive'">
                                    {{ item.enable == 0 ? '启用' : '禁用' }}
                                </span>
                                <!-- 新增Switch开关 -->
                                <el-switch v-model="item.enable" :active-value="0" :inactive-value="1"
                                    :before-change="() => { handleStatusChange(item) }" style="margin-left: 8px;" />
                            </div>
                            <el-button type="text" icon="EditPen" @click="openDiolg('编辑', item)">编辑</el-button>
                            <el-button type="text" icon="Delete" @click="deleteAccount(item)">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="title head-title bottom-border">其他对比库</div>
            <div class="operation-box">
                <!-- 修改循环数据源为mockList -->
                <div class="operation-item" v-for="(item, index) in mockList" :key="item.id">
                    <div class="item-main">
                        <div class="left-info">
                            <div class="text-info">
                                <p class="shop-name">{{ item.compareName }}</p>
                                <p class="contact-info">创建于 | {{ item.createTime }}</p>
                                <p class="contact-info">共{{ item.productNums }}款产品</p> <!-- 动态显示产品数 -->
                                <p class="contact-info">共{{ item.childNums }}个系列</p> <!-- 动态显示系列数 -->
                            </div>
                        </div>
                        <div class="right-actions">
                            <!-- 状态标签与Switch组合 -->
                            <div class="status-group">
                                <span class="status-tag" :class="item.enable == 0 ? 'active' : 'inactive'">
                                    {{ item.enable == 0 ? '启用' : '禁用' }}
                                </span>
                                <!-- 新增Switch开关 -->
                                <el-switch v-model="item.enable" :active-value="0" :inactive-value="1"
                                    :before-change="() => { handleStatusChange(item) }" style="margin-left: 8px;" />
                            </div>
                            <el-button type="text" icon="EditPen" @click="openDiolg('编辑', item)">编辑</el-button>
                            <el-button type="text" icon="Delete" @click="deleteAccount(item)">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <pagination :total="totals" v-model:page="initParam.pageNum" v-model:limit="initParam.pageSize"
                @pagination="getTableList" />
        </div>

    </div>
</template>

<style scoped>
.operation-box {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    /* 项间距 */
    padding: 20px;
}

.operation-item {
    width: calc((100% - 40px) / 3);
    border: 1px solid #f0f2f5;
    /* 更浅的边框颜色 */
    border-radius: 12px;
    /* 更大的圆角 */
    padding: 20px;
    /* 增加内边距 */
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
    /* 更柔和的阴影 */
    transition: all 0.3s ease;
    /* 添加过渡动画 */

    &:hover {
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
        /* 悬停阴影加深 */
        transform: translateY(-2px);
        /* 轻微上移效果 */
    }
}

.item-main {
    align-items: center;
    /* 垂直居中对齐 */
}

.left-info .text-info {
    .shop-name {
        font-size: 18px;
        /* 增大标题字号 */
        margin-bottom: 8px;
        /* 增加标题与其他信息的间距 */
    }

    .contact-info {
        font-size: 13px;
        /* 缩小辅助信息字号 */
        color: #909399;
        /* 更浅的辅助文字颜色 */
    }
}

.right-actions {
    flex-direction: row;
    /* 改为水平排列 */
    align-items: center;
    /* 垂直居中 */
    gap: 12px;
    /* 统一元素间距 */
}

.status-group {
    display: flex;
    /* 状态标签与Switch水平排列 */
    align-items: center;
}

.el-switch {
    --el-switch-width: 40px;
    /* 调整开关宽度 */
    --el-switch-height: 20px;
    /* 调整开关高度 */
}

.status-tag {
    font-size: 14px;
    padding: 2px 8px;
    border-radius: 12px;
}

.status-tag.active {
    background: #e6f4ea;
    color: #67c23a;
}

.status-tag.inactive {
    background: #fde2e2;
    color: #f56c6c;
}

.auth-series {
    margin-top: 12px;
}

.series-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
}
</style>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, toRefs } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, tabBarProps } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import {
    ColumnProps,
} from "@/components/ProTable/interface";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    listSupplier,
    getSupplier,
    delSupplier,
    addSupplier,
    updateSupplier
} from "@/api/zc/SupplierMagment";
import {
    listCompare,
    getCompare,
    delCompare,
    addCompare,
    updateCompare,
    enable
} from "@/api/zc/compare";
import {
    listDealerManage,
} from "@/api/system/dealerManage";
import {
    listCarrier,
    getCarrier,
    delCarrier,
    addCarrier,
    updateCarrier
} from "@/api/zc/operation";
import { getDicts } from "@/api/system/dict/data";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { useHandleData } from "@/hooks/useHandleData";
import CryptoJS from 'crypto-js';
const proxy = getCurrentInstance()?.proxy;
const emit = defineEmits(["changeItem"]);
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));
const publicKey = import.meta.env.VITE_APP_PUBLICKEY; //引入公钥
const router = useRouter();
const ExcelRef = ref(null);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<any>();
let memberFiled = { label: "dealerName", value: "id", labelName: "dealerName", autoLable: false };
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
    compareName: '',  // 经销商名称
    belong: '',       // 所属机构ID
    status: '',       // 所属状态（0/1）
    pageNum: 1,
    pageSize: 6,
});
const totals = ref(0);
const resetQuery = () => {
    initParam.compareName = '';
    initParam.belong = '';
    initParam.status = '';
    getTableList();
}
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
    return { list: data.rows, total: data.total };
};

const handleStatusChange = async (item: any) => {
    console.log("item",item)
    try {
        // 添加二次确认弹窗
        await ElMessageBox.confirm(
            `确定要将状态切换为${item.enable == '1' ? '启用' : '禁用'}吗？`,
            '状态切换确认',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        // 用户确认后调用接口
        await enable({ id: item.id, enable: item.enable == '1' ? '0' : '1'});  /* 调用更新状态接口 */
        ElMessage.success(`状态切换为${item.enable == '1' ? '启用' : '禁用'}成功`);
        getTableList();  /* 刷新列表数据 */
        return true;  // 返回 true 表示状态切换成功
    } catch (error) {
        // 区分用户取消操作和接口错误
        if (error !== 'cancel') {
            ElMessage.error('状态切换失败');
        }
        return false;  // 阻止继续执行
    }
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const ableList = ref([])
const getTableList = async () => {
    let { rows, total } = await listCompare({ ...initParam, enable: 1 });
    // mockList.value = rows.map((item: any) => {
    //     return {
    //         ...item,
    //         optionalSeries: item.optionalSeries.split(','),
    //     };
    // });
    mockList.value = rows;
    totals.value = total;

    let { rows: data } = await listCompare({ ...initParam, enable: 0 });
    ableList.value = data;
    // return listSupplier(params);
};
getTableList();
const templateParams = {
    templateName: "demo模板",
    templateUrl: "system/user/importTemplate",
    templateType: 0,
    templateObj: {}
}


const changeStatus = async (row: any, key: string) => {
    // await useHandleData(updateSign, { ...row, key: row[key] == 1 ? 0 : 1 }, `切换状态`);
    await enable({ ...row, key: row[key] == 1 ? 0 : 1 });
    ElMessage.success({ message: `调整状态成功！` });
    proTable.value?.getTableList();
};
// 删除用户信息
const deleteAccount = async (params: any) => {
    const ids = params.id
    await useHandleData(delCompare, ids, '是否删除编号为' + ids + '的数据');
    getTableList();
};
//模拟 调用接口
const PromiseDel = () => new Promise((resolve, reject) => resolve(true))

/** 导出按钮操作 */
function handleExport() {
    proxy.download("system/user/export", {

    }, `user_${new Date().getTime()}.xlsx`);
};

const openDiolg = async (title: string, rowData: any) => {
    let params: any = {
        title,
        isView: title === "查看",
        rowData: { ...rowData },
        api: title === "新增" ? addCompare : title === "编辑" ? updateCompare : undefined,
        getTableList: proTable.value?.getTableList,
    };
    if (title === "新增") {
        params.rowData.selectedSeries = []

    } else {
        let { data } = await getCompare(rowData.id)
        params.rowData = data;
        // params.rowData.availableSeries =[];
        // params.rowData.password = CryptoJS.AES.decrypt(params.rowData.password, publicKey).toString(CryptoJS.enc.Utf8), { expires: 30 }
        // params.rowData.selectedSeries = params.rowData.optionalSeries.split(',')
        params.rowData.selectedSeries = data.detailList;
        console.log(params.rowData)
    }
    emit("changeItem", "1", params, title);
};

// 新增模拟数据（包含图片地址、店名、联系方式等）
const mockList = ref([
    // {
    //     id: 1,
    //     logo: 'https://via.placeholder.com/50x50?text=杭州旗舰店', // 占位图服务
    //     shopName: '杭州旗舰店',
    //     contactName: '张经理',
    //     phone: '138-1234-5678',
    //     status: '1', // 1=启用
    //     authSeries: ['奢华印象', '经典系列']
    // },
    // {
    //     id: 2,
    //     logo: 'https://via.placeholder.com/50x50?text=上海体验店',
    //     shopName: '上海体验店',
    //     contactName: '李总监',
    //     phone: '139-8765-4321',
    //     status: '0', // 0=禁用
    //     authSeries: ['普通质感', '现代简约']
    // },
    // {
    //     id: 3,
    //     logo: 'https://via.placeholder.com/50x50?text=广州形象店',
    //     shopName: '广州形象店',
    //     contactName: '王店长',
    //     phone: '186-0000-1111',
    //     status: '1',
    //     authSeries: ['高端定制', '轻奢风尚']
    // },
    // 可根据需要添加更多模拟数据
]);
</script>
